package com.nhic.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
/*
* 自定义控制器异常处理类，控制器出现异常，跳转到自定义的错误页面
* */
//该注解会拦截有@Controller注解的类
@ControllerAdvice
public class ControllerExceptionHandler {
//创建日志对象，注意是导入slf的包
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //表示这个方法是做异常处理的。
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        //设置日志,出现error级别的日志，会把所设置的参数输出到控制台
        logger.error("Request URL : {}, Exception : {}",request.getRequestURL(),e);
    //用工具查找异常类是否有响应状态的注解——如@ResponseStatus(HttpStatus.NOT_FOUND)，如果有，则抛出该异常
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}
